package game.module.sss.procesor;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.sss.bean.SssRound;
import game.module.sss.logic.SssDataManager;
import game.module.sss.logic.SssDismissRoomManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageSss.C2SVoteDissSssroom;
import lua.LuaMessageSss.PushVoteDissSssroom;
import lua.LuaMessageSss.S2CVoteDissSssroom;

@MsgCodeAnn(msgcode = C2SVoteDissSssroom.id, accessLimit = 500)
public class SssForceDismissRoomProcessor  extends PlayingRoleMsgProcessor{

	private static Logger logger = LoggerFactory.getLogger(SssForceDismissRoomProcessor.class);
	
	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {
		// TODO Auto-generated method stub
		int playerId = playingRole.getId();
		logger.info("mj force to dismiss room,playerId={}", playerId);
		C2SVoteDissSssroom reqMsg = C2SVoteDissSssroom.parse(requestMessage);
		byte vote = reqMsg.vote;
		// 房间是否存在
		// 房间是否存在
		SssRound mjround = SssDataManager.getInstance().getNnRoom(playerId);
		if (mjround == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		List<Integer> players = mjround.getPlayerIds();
		boolean votediss[] = mjround.getVotediss();
		int currents = players.indexOf(playerId);
		
		S2CVoteDissSssroom msg = new S2CVoteDissSssroom();
		playingRole.writeAndFlush(msg.build(playingRole.alloc()));
		
		PushVoteDissSssroom pushmsg = new PushVoteDissSssroom();
		pushmsg.index = (byte) currents;
		pushmsg.result = vote;
		if(vote == 0) {
			SssDismissRoomManager.getInstance().cancleDissMiss(mjround.getRoomUuid());
			mjround.setVoteDissPlayer((byte)0);
			mjround.setCreateVotedissTime(0);
			Arrays.fill(votediss, false);
		}else {
			SssDismissRoomManager.getInstance().createRemoveSssRound(playerId);
			votediss[currents] = true;
		}
		for(Integer aplayer:players) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aplayer);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushmsg.build(pr.alloc()));
				// 推送关于出牌的信息
			}
		}
	    for(boolean flag:votediss) {
	    	if(!flag)
	    		return;
	    }
	    SssDismissRoomManager.getInstance().advanceCancle(playerId);
		//MjLogic.getInstance().testRoundOver(mjround);
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
